<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/17
 * Time: 17:23
 */

namespace App\Services;



use Obs\ObsClient;

/**
 * 华为OBS服务类
 * Class ALiOssUploadService
 * @package App\Services
 */
class HuaWeiObsService
{

    protected $ak = "VNMKYZQ8IFYQE5JWZ77U";//华为云帐号Access Key
    protected $sk = "Nwtl3FmJ2k6fPHMOPM9YGRQaOHpV0uH8CbrGW3ZZ";//华为云帐号Secret Access Key
    protected $bucket = "video-source";//对象存储的桶名称
    //直播服务应用区域和各服务的终端节点
    protected $endpoint = 'https://obs.cn-north-4.myhuaweicloud.com';
    protected $client;

    public function __construct(){
        $ak = $this->ak;
        $sk = $this->sk;
        $endpoint = $this->endpoint;

        //创建ObsClient实例
        $this->client = new ObsClient([
            'key' => $ak,
            'secret' => $sk,
            'endpoint' => $endpoint
        ]);
    }

    /**
     * 上传文件
     * @param $file 文件对象
     */
    public function putObject($file){
        $name = $file->getClientOriginalName();//文件原名称
        $source_file = $file->getPathname();//待上传对象的源文件路径
        $file_name = time() . rand(1111,9999) .'.'. $file->getClientOriginalExtension();//重新生成文件名
        $path = 'uploads/' . date('Ymd') .'/'. $file_name;
        $object = $this->client;
        $resp = $object->putObject([
            'Bucket' => $this->bucket,//桶名称
            'Key' => $path,//对象名 路径+文件名+文件后缀 如:user/pic123.png
            'SourceFile' => $source_file,  //待上传对象的源文件路径。 localfile为待上传的本地文件路径，需要指定到具体的文件名
            'ACL' => 'public-read' // 设置对象ACL为"公共读"
        ]);
        $res = [
            'code'=>500,
        ];
        if ($resp['HttpStatusCode'] == 200){
            $res = [
                'code'=>200,
                'url' => '/' . $path,
                'ol_url' => env('OBSURL') . '/' . $path,
                'name'=>$name//文件原名称
            ];
        }
        return $res;
    }

}
